package cn.ciee.f4.orchard.device;

import java.text.DecimalFormat;
import java.util.Random;

import cilico.tools.*;

import cn.ciee.f4.orchard.config.DebugConfig;
import cn.ciee.f4.orchard.entity.PositionLocation;
import cn.ciee.f4.orchard.entity.Tree;

public class DeviceManager {

	private Tree tree = null;
	public boolean isError = false;
	public String errorMsg = "";

	public DeviceManager() {
		tree = new Tree();
	}

	public DeviceManager(Tree tree) {
		this.tree = tree;
	}

	public boolean readRfid() {
		if (DebugConfig.SimulateRFID) {
			Random random = new Random();
			tree.mRfid = random.nextInt(1000);
			return true;
		} else {
			tree.mRfid=RFID.readRFID();
			if(tree.mRfid==-1)
				return false;
			else 
				return true;
		}
	}

	public boolean readZigbeeInfo(String info) {
		if (DebugConfig.SimulateZigbee) {
			Random random = new Random();
			random.setSeed(System.currentTimeMillis());
			DecimalFormat df=new DecimalFormat("#.00");
			tree.mSoilTemperature =Double.parseDouble(df.format(52 * random.nextDouble()));
			tree.mSoilHumidity = Double.parseDouble(df.format(45 * random.nextDouble()));
			tree.mAirTemperature = Double.parseDouble(df.format(52 * random.nextDouble()));
			tree.mAirHumidity = Double.parseDouble(df.format(45 * random.nextDouble()));
			return true;
		} else {
			if(Zigbee.readZigbee(info, tree)){
				return true;
			}else{
				errorMsg=Zigbee.lastErrorMessage;
				return false;
			}
		}
	}

	public boolean setLocation(PositionLocation location) {
		tree.mLat = location.mLat;
		tree.mLng = location.mLng;
		tree.mLocationDetails = location.mLocationDetails;
		return true;
	}

	public Tree getTree() {
		return tree;
	}
}
